<?php
/**
 * Created by PhpStorm.
 * User: 84071
 * Date: 2018-08-15
 * Time: 22:51
 */
namespace app\admin\controller;

use app\common\controller\Adminbase;
use app\common\extend\Wxreturn;
use app\common\model\WxMenu as cxModel;
use think\Loader;
use weixinhack\WxBase;

class WxMenu extends Adminbase {
    protected $beforeActionList = [
        'btnyz'  =>  ['only'=>'index,add,edit'],
    ];
    protected function btnyz(){
        $btn = $this->btnauth('add,edit,del');
        $this->assign('btn',$btn);
    }
    public function index(){
        $cxmodel = new cxModel();
        $wxmodel = new WxBase();
        $wxtoken = $wxmodel->access_token($this->webdb['wxappid'],$this->webdb['wxappsecret']);
        $menus = $cxmodel->where('title','wxmenu')->find()->toArray();
        if(empty($menus)){
            $menus = $wxmodel->get_menus($wxtoken);
        }else{
            $menu = unserialize($menus['conf']);
            $menus['menu'] = json_decode($menu,true);
        }
        if(request()->isPost()){
            $data = input('post.');
            $data = datatrim($data);
            foreach ($data['button'] as $k => $v){
                $val = null;
                if(!empty($v['sub_button'])){
                    $val['name'] = $v['name'];
                    foreach($v['sub_button'] as $v1){
                        $val['sub_button'][] = $v1;
                    }
                    $enddata['button'][] = $val;
                }else{
                    $val = $v;
                    $enddata['button'][] = $val;
                }
            }
            $retxt = null;
            $enddata = json_encode($enddata,JSON_UNESCAPED_UNICODE);
            if($data['wxsave'] == '1'){
                $addmenu = $wxmodel->post_menu($enddata,$wxtoken);
                if($addmenu['errcode'] == '0'){
                    $retxt = ",并发布成功";
                }else{
                    $wxcode = new Wxreturn();
                    $retxt = $wxcode->wxreturn($addmenu['errcode']);
                }
            }
            $data['title'] = 'wxmenu';
            $data['wxid'] = $this->webdb['wxid'];
            $data['conf'] = serialize($enddata);
            if(empty($data['id'])){
                if($cxmodel->allowField(true)->save($data)){
                    $this->success("菜单保存成功{$retxt}！");
                }else{
                    $this->error("菜单保存失败{$retxt}");
                }
            }else{
                if($cxmodel->allowField(true)->isUpdate(true)->save($data,['id'=>$data['id']])){
                    $this->success("菜单保存成功{$retxt}！");
                }else{
                    $this->error("菜单保存失败{$retxt}");
                }
            }
        }
        if(empty($menus['menu'])){
            $menus['menu'] = null;
        }
        $this->assign([
            'menus' => $menus,
        ]);
        return view();
    }

}